import $api from './request'

export default async function wechatPay(id) {
  uni.showLoading()
  const { data } = await $api.post(`api/invoices/${id}/pay/huifu`, {
    gateway: 'jspay',
    trade_type: 'T_MINIAPP'
  })
  const paymentData = JSON.parse(data.payment.pay_info)
  return new Promise((resolve, reject) => {
    uni.requestPayment({
      provider: 'wxpay',
      timeStamp: paymentData.timeStamp,
      nonceStr: paymentData.nonceStr,
      package: paymentData.package,
      signType: paymentData.signType,
      paySign: paymentData.paySign,
      success: res => {
        console.log('success:' + JSON.stringify(res))
        uni.hideLoading()
        uni.showToast({
          title: '支付成功'
        }) 
        resolve(JSON.stringify(res))
      },
      fail: err => {
        console.log('fail:' + JSON.stringify(err))
        uni.hideLoading()
        uni.showToast({
          title: '支付失败',
          icon: 'none'
        })
        reject(JSON.stringify(err))
      }
    })
  })
}